<!-- 邮件服务器 -->
<template>
    <div class="main-header">
      <el-card class="box-card" style="height: 400px;" shadow="never">
        <div slot="header" class="cardHeard" style="height: 38px">
          <div>
            <span class="title">邮件设置</span>
          </div>
          <div>
            <el-button type="primary"  @click="sendClick('emailForm')">发送测试邮件</el-button>
            <el-button style="float: right; margin-left:5px;" type="primary" @click="confirmClick('emailForm')">保存设置</el-button>
          </div>
        </div>
        <div>
          <el-form :model="emailForm" :rules="emailForm.MailCenterStatus === false ? {} : rules" ref="emailForm" label-width="40%">
            <el-row :gutter="24">
              <!-- <el-col :sm="24" :md="24" :lg="24">
                <el-form-item  label="状态：" prop="status">
                    <el-switch v-model="emailForm.MailCenterStatus" @change='statusClick' active-color="" inactive-color=""></el-switch>
                </el-form-item>
              </el-col> -->
              <div> <!--  v-if="emailForm.MailCenterStatus === true" -->
                <el-col :sm="24" :md="24" :lg="24">
                  <el-form-item  label="邮件服务器：" prop="MailServer">
                    <el-input size="small" v-model="emailForm.MailServer" placeholder="请输入邮件服务器" maxlength="128"></el-input>  
                  </el-form-item>
                </el-col>
                <el-col :sm="24" :md="24" :lg="24">
                  <el-form-item  label="端口：" prop="MailPort">
                      <el-input @input="validatePort" size="small" v-model.number="emailForm.MailPort" placeholder="请输入端口" maxlength="5"></el-input>  
                      <el-checkbox style="margin-left:10px;" v-model="emailForm.MailSSL">SSL</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :sm="24" :md="24" :lg="24">
                  <el-form-item  label="发送人邮箱：" prop="MailSender">
                    <el-input size="small" v-model="emailForm.MailSender" placeholder="请输入发送人邮箱" maxlength="64"></el-input>  
                    <!-- <el-button type="primary" style="margin-left: 10px;" @click="authorization()">授权信息</el-button> -->
                  </el-form-item>
                </el-col>
                <!-- <el-col :sm="24" :md="24" :lg="24">
                  <el-form-item  label="服务器认证：" prop="MailServerAuthentication">
                      <el-switch v-model="emailForm.MailServerAuthentication" @change='MailUserClick' active-color="" inactive-color=""></el-switch>
                  </el-form-item>
                </el-col> -->
                <el-col :sm="24" :md="24" :lg="24"> <!--  v-show="emailForm.MailServerAuthentication===true" -->
                  <el-form-item  label="用户名：" prop="MailUser" :rules="emailForm.MailServerAuthentication === true? rules.MailUser: []">
                    <el-input size="small" v-model="emailForm.MailUser" placeholder="请输入用户名" maxlength="32"></el-input>  
                  </el-form-item>
                </el-col>
                <el-col :sm="24" :md="24" :lg="24"> <!--  v-show="emailForm.MailServerAuthentication===true" -->
                  <el-form-item  label="密码：" prop="MailPd" :rules="emailForm.MailServerAuthentication === true? rules.MailPd: []">
                    <el-input size="small" v-model="emailForm.MailPd" :show-password='true' autocomplete="new-password" placeholder="请输入密码" maxlength="32"></el-input>  
                  </el-form-item>
                </el-col>
              </div>
              <!-- <div style="width:90%;display:flex;justify-content: end;">
              </div> -->
            </el-row>
          </el-form> 
        </div>
        <div>
        </div>
      </el-card>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage';
import { validatePort } from "@/utils/index.js";

export default {
    data(){
        var validateSpace = (rule, value, callback) => {
            if (value == null || value == '') {
                callback(new Error('请输入服务器地址/域名'))
            }else if (value.indexOf(' ') != -1) {
                callback(new Error('服务器地址/域名不允许输入空格'))
            }else{
                callback();
            }
        }
        var validateSpace1 = (rule, value, callback) => {
            if (value == null || value == '') {
                callback(new Error('请输入发送人邮箱'))
            }else if (value.indexOf(' ') != -1) {
                callback(new Error('发送人邮箱不允许输入空格'))
            }else{
                callback();
            }
        }
        var validateSpace2 = (rule, value, callback) => {
            if (value == null || value == '') {
                callback(new Error('请输入用户名'))
            }else if (value.indexOf(' ') != -1) {
                callback(new Error('用户名不允许输入空格'))
            }else{
                callback();
            }
        }
        return{
            authorizationCode: 0,
            emailForm:{
                MailCenterStatus: true, //邮件状态：开启 or 关闭
                MailServer:'',//邮件服务器
                MailPort:25,//端口
                MailSSL:false,//ssl单选
                MailSender:'',//发件人邮箱
                MailServerAuthentication: true,//是否开启认证
                MailUser:'',//用户名
                MailPd:''//密码
            },
            rules:{ //表单规则
              MailServer:{ required: true,validator:validateSpace, trigger: 'blur' },
              MailPort: { required: true, message: '请输端口，取值范围为0-65535', trigger: 'blur' },
              MailSender: { required: true, validator:validateSpace1, trigger: 'blur' },
              MailUser:{ required: true, validator:validateSpace2, trigger: 'blur' },
              MailPd:{ required: true, message: '请输入密码', trigger: 'blur' }
            },
        }
    },
    created(){
      this.getData();
    },
    methods:{
        validatePort(value){
          this.$set(this.emailForm, 'MailPort', validatePort(value) * 1)
        },
        // 获取邮件列表数据
        async getData(){
            const res = await connrequest('GetMailConfig');
            if (res.Status.StatusCode===0) {
                this.emailForm = {...res.Data}
            }
        },
        // 状态切换判断
        statusClick(val){
            if (val===false) {
              this.$nextTick(() => {
                this.rules.required = false;
                this.$refs["emailForm"].clearValidate();
                // this.$refs['ruleForm'].resetFields();
              });
            }
        },
        // 服务器认证状态判断
        MailUserClick(val){
            if (val===false) {
                this.emailForm.MailUser = '';
                this.emailForm.MailPd = '';
            }
        },
        // 授权信息
        authorization(){
          this.$confirm('是否授权使用邮箱作为收件人邮箱? 该邮箱主要用于接收告警邮件 ！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.authorizationCode = 1
            this.$message({
              type: 'success',
              message: '授权成功!'
            });
          }).catch(() => {
            this.authorizationCode = 0
            this.$message({
              type: 'info',
              message: '已取消授权'
            });          
          });
        },
        // 确定按钮修改服务器
        async confirmClick(formName){
          this.$refs[formName].validate(async(valid) => {
            if (valid) {
              const paramData = {
                  Data:{
                    ...this.emailForm
                  },
              };
              const res = await connrequest('SetMailConfig', paramData);
              if (res.Status.StatusCode===0) {
                  this.$message.success('更改成功');
                  this.getData();
              }
            } else {
                    return false;
                }
            });  
        },
        // 发送测试邮件
        sendClick(formName){
          this.$refs[formName].validate(async(valid) => {
            if (valid) {
              // 校验格式
              this.$prompt('请输入邮箱', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
                inputErrorMessage: '邮箱格式不正确',
                closeOnClickModal:false
              }).then(async({ value }) => {
                let data = {...this.emailForm};
                data.MailTestRecver = value
                const paramData = {
                  Data:data
                }
                const res = await connrequest('TestMailConfig', paramData);
                if (res.Status.StatusCode===0) {
                  this.$message.success('发送成功');
                }
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '取消输入'
                });       
              })
            } else {
                    return false;
                }
            });    
        }
    }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}
.box-card{
  // margin: 16px;
  margin-bottom: 10px !important;
}
::v-deep .el-input--small{
    width:40% !important;
}
::v-deep .el-card__header{
  padding: 10px !important;
}
.cardHeard{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-form-item{
  margin-bottom: 10px !important;
}
::v-deep .el-form-item__error{
  padding-top: 0 !important;
}

</style>